const http = require('spdy') // 若为http2则把'https'模块改为'spdy'模块 npm install spdy
const fs = require('fs')
const express = require('express')

const app = express()

const options = {
  key: fs.readFileSync(`${__dirname}/server.key`),
  cert: fs.readFileSync(`${__dirname}/server.crt`)
}

const allow = (res) => {
  res.header("Access-Control-Allow-Origin", "*")
  res.header("Access-Control-Allow-Headers", "X-Requested-With")
  res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS")
}

app.get('/option/?', (req, res) => {
	allow(res)
	let size = req.query['size']
	let delay = req.query['delay']
	// Buffer类，该类用来创建一个专门存放二进制数据的缓存区
	// 生成size * 1024 * 1024字节的二进制数据
	let buf = Buffer.alloc(size * 1024 * 1024)
	setTimeout(() => {
		//buf.toString('utf8')，将Buffer对象中保存的数据转换为字符串
		// 返给前端的是size * 1024 * 1024 字节的字符串
		res.send(buf.toString('utf8'))
	}, delay)
})

http.createServer(options, app).listen(1002, (err) => { // http2服务器端口为1002
	if (err) throw new Error(err)
	console.log('Http2 server listening on port 1002.')
})
